Component({
  data: {
    selected: 0,
    list: [
      {
        pagePath: "pages/student/profile/profile",
        text: "个人中心",
        icon: "images/profile.png",
      },
      {
        pagePath: "pages/student/transcript/transcript",
        text: "成绩单",
        icon: "images/transcript.png",
      },
      {
        pagePath: "pages/student/research/research",
        text: "科研成果",
        icon: "images/research.png",
      },
      {
        pagePath: "pages/student/application/application",
        text: "申请记录",
        icon: "images/application.png",
      },
    ],
  },
  attached() {
    // 延迟设置选中状态，确保页面已加载
    setTimeout(() => {
      this.setSelected();
    }, 100);
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset;
      let url = data.path || "";
      if (url && url.charAt(0) !== "/") {
        url = `/${url}`;
      }
      const index = data.index;

      wx.switchTab({ url });
      this.setData({
        selected: index,
      });
    },
    setSelected() {
      const pages = getCurrentPages();
      if (pages.length === 0) {
        return;
      }

      const currentPage = pages[pages.length - 1];
      if (!currentPage || !currentPage.route) {
        return;
      }

      const url = currentPage.route;
      const index = this.data.list.findIndex((item) => item.pagePath === url);
      if (index !== -1) {
        this.setData({
          selected: index,
        });
      }
    },
  },
});
